# -*- coding: utf-8 -*-

'''eof
name:已结清信贷交易最严重五级分类
code:EC86_Settled5ClassWorstCheck
tableName:
columnName:
groups:企业征信
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:已结清信贷交易最严重五级分类
eof'''

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

# 获取表信息方法
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


# 时间信息格式化方法
def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


# 数值判断方法
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def EC86_Settled5ClassWorstCheck():
    try:
        factor = []
        five_dict = {'1': u'正常', '2': u'关注', '3': u'次级', '4': u'可疑', '5': u'损失', '6': u'违约'}
        data = EC_DSJ_2D['data']
        # 借贷账户
        EDA = getTable(data, 'EDA', 1, 0)
        if EDA == [{}]:
            factor.append(None)
        elif EDA == 0:
            factor.append(0)
        else:
            ED01 = getTable(EDA[0], 'ED01', 0, 1)
            if ED01 == 0:
                factor.append(0)
            elif ED01 == [{}]:
                factor.append(None)
            else:
                for i in ED01:
                    try:
                        #  基本信息段
                        ED01A = getTable(i, 'ED01A', 1, 1)
                        # 还款表现信息段
                        ED01B = getTable(i, 'ED01B', 1, 1)
                        if ED01A == 0 or ED01B == 0:
                            factor.append(0)
                        elif ED01A == [{}] or ED01B == [{}]:
                            factor.append(None)
                        else:
                            # 账户活动状态
                            ED01AD01 = ED01A[0].get('ED01AD01')
                            # 还款表现信息
                            ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                            if ED01BH == 0:
                                factor.append(0)
                            elif ED01BH == [{}]:
                                factor.append(None)
                            else:
                                flag = []
                                five_dict_dk = {}
                                for j in ED01BH:
                                    # 日期
                                    ED01BR02 = j.get('ED01BR02')
                                    # 五级分类
                                    ED01BD01 = j.get('ED01BD01')
                                    if dateFormat(ED01BR02) is None or ED01BD01 in null_type_list:
                                        flag.append(None)
                                    else:
                                        flag.append(0)
                                        five_dict_dk.update({dateFormat(ED01BR02).strftime('%Y%m%d'): ED01BD01})
                                if 0 in flag:
                                    five_dk = five_dict_dk[max(five_dict_dk.keys())]
                                else:
                                    five_dk = None
                                if ED01AD01 in null_type_list or five_dk is None:
                                    factor.append(None)
                                else:
                                    if str(ED01AD01) == '2':
                                        factor.append(str(five_dk))
                                    else:
                                        factor.append(0)
                    except:
                        factor.append(None)
                        continue
        # 担保账户信息
        EDB = getTable(data, 'EDB', 1, 0)
        if EDB == [{}]:
            factor.append(None)
        elif EDB == 0:
            factor.append(0)
        else:
            # 担保账户信息明细单元
            ED04 = getTable(EDB[0], 'ED04', 0, 1)
            if ED04 == [{}]:
                factor.append(None)
            elif ED04 == 0:
                factor.append(0)
            else:
                for i in ED04:
                    try:
                        # 基本信息段
                        ED04A = getTable(i, 'ED04A', 1, 1)
                        # 在保责任信息段
                        ED04B = getTable(i, 'ED04B', 1, 1)
                        if ED04A == 0 or ED04B == 0:
                            factor.append(0)
                            continue
                        elif ED04A == [{}] or ED04A == [{}]:
                            factor.append(None)
                        else:
                            # 账户活动状态
                            ED04BD01 = ED04B[0].get('ED04BD01')
                            # 五级分类
                            ED04BD02 = ED04B[0].get('ED04BD02')
                            if ED04BD01 in null_type_list or ED04BD02 in null_type_list:
                                factor.append(None)
                            else:
                                if str(ED04BD01) == '2':
                                    factor.append(str(ED04BD02))
                                else:
                                    factor.append(0)
                                    continue
                    except:
                        factor.append(None)
                        continue
        factorNotNone = list(filter(lambda x: x is not None, factor))
        factorNotNoneNotZero = list(filter(lambda x: x != 0, factorNotNone))
        if len(factorNotNoneNotZero) == 0:
            return u"缺失值"
        elif len(set(factorNotNoneNotZero)) == 1 and list(set(factorNotNoneNotZero))[0] == '9':
            return u"缺失值"
        else:
            return five_dict[max(factorNotNoneNotZero)]
    except:
        return u"缺失值"


result = EC86_Settled5ClassWorstCheck()

